package com.iyao_app.mvp.other;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.iyao_app.Friends.ChatActivity;
import com.iyao_app.R;
import com.iyao_app.adapter.LiuyanAdapter;
import com.iyao_app.adapter.OftenAdapter;
import com.iyao_app.adapter.PictureAdapter;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.CallList;
import com.iyao_app.entry.DemoData;
import com.iyao_app.entry.HomeData;
import com.iyao_app.entry.Other;
import com.iyao_app.entry.PreviewData;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.SearchData;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.im.activity.AttentionActivity;
import com.iyao_app.mvp.info.WhoCallMeActivity;
import com.iyao_app.mvp.preview.ImageViewPagerActivity;
import com.iyao_app.mvp.signlist.CustomListActivity;
import com.iyao_app.mvp.signlist.SignMapListActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.FrescoImageLoader;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.TimeFormat;
import com.iyao_app.util.ToastUtil;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.PopupWindowUtils;
import com.iyaowoqu.base_library.util.Utils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.rockerhieu.emojicon.EmojiconEditText;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/30.
 */

public class OtherHomeActivity extends BaseActivityWithHead {
    @BindView(R.id.iv_next)
    TextView mIvNext;
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.tv_id)
    TextView mTvId;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rv_horizontal)
    RecyclerView mRvHorizontal;
    @BindView(R.id.iv_qian_dao)
    ImageView mIvQianDao;
    @BindView(R.id.iv_gu_shi)
    ImageView mIvGuShi;
    @BindView(R.id.iv_guan_zhu)
    ImageView mIvGuanZhu;
    @BindView(R.id.tv_often_go)
    TextView mTvOftenGo;
    @BindView(R.id.rv_who_see_me)
    RecyclerView mRvWhoSeeMe;
    @BindView(R.id.tv_who_see_me)
    TextView mTvWhoSeeMe;
    @BindView(R.id.tv_more)
    TextView mTvMore;
    @BindView(R.id.rv_more)
    RecyclerView mRvMore;
    @BindView(R.id.sdv_head)
    SimpleDraweeView mSdvHead;
    @BindView(R.id.tv_send)
    TextView mTvSend;
    @BindView(R.id.iv_more)
    ImageView mIvMore;
    @BindView(R.id.rl_1)
    RelativeLayout mRl1;
    @BindView(R.id.nest_scroll)
    NestedScrollView mNestScroll;

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.appbarlayout)
    AppBarLayout mAppbarlayout;
    @BindView(R.id.lin_1)
    LinearLayout mLin1;
    @BindView(R.id.main_content)
    CoordinatorLayout mMainContent;
    @BindView(R.id.et_input)
    EmojiconEditText mEtInput;
    @BindView(R.id.iv_sex)
    ImageView mIvSex;
    @BindView(R.id.rl_no_see)
    LinearLayout mRlNoSee;
    @BindView(R.id.rl_have_see)
    LinearLayout mRlHaveSee;
    @BindView(R.id.lin_2)
    LinearLayout mLin2;
    @BindView(R.id.rl_more)
    LinearLayout mRlMore;
    @BindView(R.id.iv_la_hei)
    ImageView iv_la_hei;


    private boolean isUpdate = true;
    private PictureAdapter pictureAdapter;
    private LiuyanAdapter adapter;
    private String id;
    private OftenAdapter oftenAdapter;
    private List<String> images;
    private Other other;
    private User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_home);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        id = getIntent().getStringExtra(Contants.TYPE);
        user = DbUtil.getUser();
        LogUtil.e("====id===" + id);
        getData();
        mTvId.setText(id);

        mRvMore.setNestedScrollingEnabled(false);
        mRvMore.setFocusable(false);
        mRvHorizontal.setFocusable(false);
        banner.setFocusable(false);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(9, StaggeredGridLayoutManager.VERTICAL);
        pictureAdapter = new PictureAdapter(this, null);
        mRvHorizontal.setAdapter(pictureAdapter);
        mRvHorizontal.setLayoutManager(staggeredGridLayoutManager);
        if (user.id.equals(id)) {
            iv_la_hei.setVisibility(View.GONE);
        } else {
            iv_la_hei.setVisibility(View.VISIBLE);
        }
        banner.setImageLoader(new FrescoImageLoader());
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.ZoomOutSlide);
        banner.isAutoPlay(false);


        pictureAdapter.setOnPictureSelectListener(new PictureAdapter.PictureSelectListener() {
            @Override
            public void onSelect(int position) {
                LogUtil.e("====" + position);
                banner.setCurrentItem(position);
            }
        });
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                LogUtil.e("====" + position);
                if (images != null && images.size() > 0) {
                    PreviewData previewData = new PreviewData();
                    previewData.image = images;
                    previewData.position = position;
                    Intent intent = new Intent(OtherHomeActivity.this, ImageViewPagerActivity.class);
                    intent.putExtra(Contants.CLASS_TYPE, previewData);
                    startActivity(intent);
                }

            }
        });
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                LogUtil.e("==onPageSelected==" + position);
                for (int i = 0; i < pictureAdapter.data.size(); i++) {
                    DemoData demoData = pictureAdapter.data.get(i);
                    if (position == i) {
                        demoData.setSelect(true);
                    } else {
                        demoData.setSelect(false);
                    }
                    pictureAdapter.notifyDataSetChanged();
                }
                for (DemoData datum : pictureAdapter.data) {
                    LogUtil.e("====" + datum.toString());

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        adapter = new LiuyanAdapter(null);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvMore.setLayoutManager(manager);
        mRvMore.setAdapter(adapter);
//        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.isFirstOnly(false);

        oftenAdapter = new OftenAdapter(null);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvWhoSeeMe.setLayoutManager(layout);
        mRvWhoSeeMe.setAdapter(oftenAdapter);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.sdv_head) {
                    CallList item = (CallList) adapter.getItem(position);
                    Intent intent = new Intent(OtherHomeActivity.this, OtherHomeActivity.class);
                    intent.putExtra(Contants.TYPE, item.sayHelloFromUserId);
                    startActivity(intent);
                }
            }
        });
    }

    @OnClick({R.id.iv_qian_dao, R.id.iv_gu_shi, R.id.iv_guan_zhu, R.id.lin_1, R.id.tv_more, R.id.sdv_head, R.id.tv_send, R.id.iv_la_hei, R.id.iv_next})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.iv_qian_dao:
                intent = new Intent(this, SignMapListActivity.class);
                intent.putExtra(Contants.TYPE, id);
                startActivity(intent);
                break;
            case R.id.iv_gu_shi:
                intent = new Intent(this, CustomListActivity.class);
                intent.putExtra(Contants.TYPE, id);
                startActivity(intent);
                break;
            case R.id.iv_guan_zhu:
                intent = new Intent(this, AttentionActivity.class);
                intent.putExtra(Contants.TYPE, 1);
                intent.putExtra(Contants.CLASS_TYPE, id);
                startActivity(intent);
                break;
            case R.id.tv_more:
                intent = new Intent(OtherHomeActivity.this, WhoCallMeActivity.class);
                intent.putExtra(Contants.TYPE, id);
                startActivity(intent);
                break;
            case R.id.sdv_head:

                break;
            case R.id.tv_send:
                sayHello();
                break;
            case R.id.lin_1://常去的地方

                break;
            case R.id.iv_la_hei:
                lahei();
                break;
            case R.id.iv_next:
                clickNext();
                break;
        }
    }

    private void clickNext() {
        switch (other.friendShip) {
            case -1:
                guanzhu();

                break;
            case 1:
                cancleFriend();

                break;
            case 4:
                Intent intent = new Intent(OtherHomeActivity.this, ChatActivity.class);
                intent.putExtra("username", id + "");
                intent.putExtra("nickname", other.nickname);
                intent.putExtra("favicon", other.avatarUrl);
                startActivity(intent);
                break;
        }
    }

    private void getOften() {

        NetUtils.getInstance().oftenArrive(id, 116.452784, 39.909134, Contants.RADIUS, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {//没有数据
                        List<SearchData> oftenData = (List<SearchData>) model.getModelList();
                        if (oftenData == null || oftenData.size() == 0) {
                            mRlNoSee.setVisibility(View.VISIBLE);
                            mRlHaveSee.setVisibility(View.GONE);
                        } else {
                            oftenAdapter.addData(oftenData);
                            mRlNoSee.setVisibility(View.GONE);
                            mRlHaveSee.setVisibility(View.VISIBLE);
                        }

                    } else {
                        mRlNoSee.setVisibility(View.VISIBLE);
                        mRlHaveSee.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, SearchData.class);
    }

    private void sayHello() {
        LogUtil.e("=====" + mEtInput.getText() + "====");


        if (TextUtils.isEmpty(mEtInput.getText().toString().trim())) {
            Toast.makeText(this, "请输入打招呼内容", Toast.LENGTH_SHORT).show();
            return;
        }
//        mTvLocation.setText();
        if (user == null) return;
        showDialog();
        NetUtils.getInstance().sayHello(id, user.id, mEtInput.getText().toString().trim(), new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                closeDialog();
                if (code == Contants.SUCCESS_CODE) {
                    Toast.makeText(OtherHomeActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                    mEtInput.setText("");
                    callList();
                }
            }

            @Override
            public void onFail(String message, int code) {
                closeDialog();
            }
        }, null);
    }

    private void getData() {

        if (user == null) return;
        NetUtils.getInstance().getOtherInfo(user.id, id, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model == null) return;
                    other = model.getModel();
                    if (other != null) {
                        callList();
                        getOften();
                        images = new ArrayList<>();
                        List<DemoData> dataList = new ArrayList<>();
                        if (!TextUtils.isEmpty(other.avatarUrl)) {
                            images.add(other.avatarUrl);
                            dataList.add(new DemoData(true, other.avatarUrl));
                            try {
                                Uri uri = Uri.parse(other.avatarUrl);
                                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                                        .setResizeOptions(new ResizeOptions(200, 200))
                                        .build();
                                PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                                        .setOldController(mSdvHead.getController())
                                        .setImageRequest(request)
                                        .build();
                                mSdvHead.setController(controller);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        int age = 0;
                        if (other.birthday != 0) {
                            age = TimeFormat.getAgeFromBirthTime(other.birthday);
                            LogUtil.e("other.birthday" + other.birthday + "===" + age);
                        }
                        mTvName.setText(other.nickname);
                        setShip();


                        if (other.sex == 1) {
                            mIvSex.setImageResource(R.mipmap.ic_boy);
                        } else {
                            mIvSex.setImageResource(R.mipmap.ic_girl);
                        }
                        mTvMoney.setText(String.valueOf(other.goldCount));
                        String s = null;
                        if (TextUtils.isEmpty(other.district) && TextUtils.isEmpty(other.city)) {
                            s = String.format("%d，%s", age, getString(R.string.from_huo_xing));
                            mTvLocation.setText(s);
                        } else {
                            s = String.format("%d，%s %s", age, other.city, other.district);
                            mTvLocation.setText(s);
                        }


                        if (other.fileUrlList != null && other.fileUrlList.size() != 0) {
                            for (int i = 0; i < other.fileUrlList.size(); i++) {
                                images.add(other.fileUrlList.get(i));
                                dataList.add(new DemoData(false, other.fileUrlList.get(i)));
                            }
                        }

                        banner.setImages(images);
                        banner.start();
                        pictureAdapter.append(dataList);
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, Other.class);
    }

    private void setShip() {
        switch (other.friendShip) {
            case -1:
                if (id.equals(user.id)) {
                    mIvNext.setVisibility(View.GONE);
                } else {
                    mIvNext.setText("关注");
                    mIvNext.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                    mIvNext.setVisibility(View.VISIBLE);
                }

                break;
            case 2:
                if (id.equals(user.id)) {
                    mIvNext.setVisibility(View.GONE);
                } else {
                    mIvNext.setText("关注");
                    mIvNext.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                    mIvNext.setVisibility(View.VISIBLE);
                }

                break;
            case 5:
                if (id.equals(user.id)) {
                    mIvNext.setVisibility(View.GONE);
                } else {
                    mIvNext.setText("关注");
                    mIvNext.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                    mIvNext.setVisibility(View.VISIBLE);
                }

                break;
            case 1:
                mIvNext.setText("已关注");
                mIvNext.setTextColor(ResourcesUtils.getColor(R.color.white));
                mIvNext.setVisibility(View.VISIBLE);
                break;
            case 4:
                mIvNext.setText("聊天");
                mIvNext.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                mIvNext.setVisibility(View.VISIBLE);
                break;

        }
    }

    private void callList() {

        NetUtils.getInstance().sayHelloList(id, 1, 5, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        HomeData homeData = model.getModel();
                        if (homeData != null) {
                            List<CallList> list = homeData.getList();
                            if (list == null || list.size() == 0) {
                                mRlMore.setVisibility(View.VISIBLE);
                                mRvMore.setVisibility(View.GONE);
                                mTvMore.setVisibility(View.GONE);
                            } else {
                                adapter.replaceData(list);
                                mRlMore.setVisibility(View.GONE);
                                mRvMore.setVisibility(View.VISIBLE);
                                mTvMore.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mTvMore.setVisibility(View.GONE);
                            mRlMore.setVisibility(View.VISIBLE);
                            mRvMore.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, HomeData.class);
    }

    private void lahei() {

        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(OtherHomeActivity.this, R.layout.item_popupwindow, mMainContent)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                .location(Gravity.BOTTOM, 0, Utils.getBottomStatusHeight(this))
                .focuseAble(true)
                .Animation(PopupWindowUtils.ANIMATION_BOTTOM)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {
                        switch (id) {
                            case R.id.pop_financial://确认
                                showDialog();
                                Observable.timer(1, TimeUnit.SECONDS)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribeOn(Schedulers.newThread())
                                        .subscribe(new Consumer<Long>() {

                                            @Override
                                            public void accept(Long aLong) throws Exception {
                                                Toast.makeText(OtherHomeActivity.this, "已举报", Toast.LENGTH_SHORT).show();
                                                closeDialog();
                                            }
                                        });
                                popupWindowUtils.dissMissPopWindow();
                                break;
                            case R.id.pop_manage://取消
                                popupWindowUtils.dissMissPopWindow();
                                break;
                        }
                    }
                }, R.id.pop_financial, R.id.pop_manage)
                .show();
        View popView = popupWindowUtils.getPopView();
        TextView title = popView.findViewById(R.id.pop_computer);
        title.setText(R.string.la_ru_hei_ming_dan);
        TextView confirm = popView.findViewById(R.id.pop_financial);
        confirm.setText(R.string.ju_bao);
    }

    private void cancleFriend() {

        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(OtherHomeActivity.this, R.layout.item_popupwindow, mMainContent)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                .location(Gravity.BOTTOM, 0, Utils.getBottomStatusHeight(this))
                .focuseAble(true)
                .Animation(PopupWindowUtils.ANIMATION_BOTTOM)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {
                        switch (id) {
                            case R.id.pop_financial://确认
                                unfollowFriend();
                                popupWindowUtils.dissMissPopWindow();
                                break;
                            case R.id.pop_manage://取消
                                popupWindowUtils.dissMissPopWindow();
                                break;
                        }
                    }
                }, R.id.pop_financial, R.id.pop_manage)
                .show();
    }

    private void guanzhu() {
        String userId = String.valueOf(id);
        NetUtils.getInstance().followFriend(userId, other.nickname, other.avatarUrl, other.sex, new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response, final ResultModel model) {
                ToastUtil.showToast(OtherHomeActivity.this, "关注成功");
                if (other.friendShip == 5) {

                } else {
                    other.friendShip = 1;
                }

                setShip();
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);
    }

    private void unfollowFriend() {
        String userId = String.valueOf(id);
        NetUtils.getInstance().unfollowFriend(userId, new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response, final ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    ToastUtil.showToast(OtherHomeActivity.this, "取消关注成功");
                    other.friendShip = -1;
                    setShip();
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);
    }

}
